package com.hcc.flow.server.controller.sys;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.hcc.flow.server.annotation.LogAnnotation;
import com.hcc.flow.server.annotation.Original;
import com.hcc.flow.server.common.enums.DataStatusType;
import com.hcc.flow.server.common.enums.IfStatusType;
import com.hcc.flow.server.common.model.ApiResult;
import com.hcc.flow.server.common.page.table.PageTableHandler;
import com.hcc.flow.server.common.page.table.PageTableRequest;
import com.hcc.flow.server.common.page.table.PageTableResponse;
import com.hcc.flow.server.common.utils.CommUtil;
import com.hcc.flow.server.common.utils.StringUtilsV2;
import com.hcc.flow.server.common.vo.SelectVO;
import com.hcc.flow.server.common.where.PublicWhere;
import com.hcc.flow.server.dao.sys.ParaTypeDao;
import com.hcc.flow.server.dao.sys.ParaValueDao;
import com.hcc.flow.server.model.common.LoginUser;
import com.hcc.flow.server.model.sys.ParaValue;
import com.hcc.flow.server.utils.UserUtil;
import com.hcc.flow.server.vo.sys.ParaTypeVO;
import com.hcc.flow.server.vo.sys.ParaValueDetailVO;

import io.swagger.annotations.ApiOperation;

/**
 * 参数管理
 * 
 * @author Administrator
 *
 */
@RestController
@RequestMapping("/paraValue")
public class ParaValueController {
	@Autowired
	private ParaTypeDao paraTypeDao;
	@Autowired
	private ParaValueDao paraValueDao;
	
	@LogAnnotation
	@PostMapping
	@ApiOperation(value = "参数-保存")
	//@PreAuthorize("hasAuthority('sys:paraValue:add')")
	public ApiResult<?> save(@RequestBody ParaValue paraValue) {
		if (paraValue == null) {
			return ApiResult.error("新增数据不能为空");
		}else if(StringUtilsV2.isBlank(paraValue.getParaCode())){
			return ApiResult.error("参数编码不能为空");
		}
		ParaTypeVO paraTypeVO = paraTypeDao.getById(paraValue.getParaTypeId());
		if(paraTypeVO != null && paraTypeVO.getParaTypeName().contains("分辨率")){
			if(!paraValue.getParaName().contains("*") 
					|| paraValue.getParaName().indexOf("*") != paraValue.getParaName().lastIndexOf("*")
					|| paraValue.getParaName().indexOf("*") == 0
					|| paraValue.getParaName().indexOf("*") == paraValue.getParaName().length()-1){
				return ApiResult.error("分辨率格式必须是（数字*数字）");
			}else{
				String f = paraValue.getParaName().substring(0, paraValue.getParaName().indexOf("*"));
				if(!CommUtil.isNumeric(f)){
					return ApiResult.error("分辨率格式必须是（数字*数字）");
				}
				String l = paraValue.getParaName().substring(paraValue.getParaName().indexOf("*")+1);
				if(!CommUtil.isNumeric(l)){
					return ApiResult.error("分辨率格式必须是（数字*数字）");
				}
			}
		}
		LoginUser loginUser = UserUtil.getLoginUser();
		paraValue.setCreateUserId(loginUser.getUserId());
		String paraId = paraValueDao.getIdByCodeAnd(paraValue.getParaCode(),paraValue.getParaTypeId());
		if(StringUtilsV2.isNotBlank(paraId)){
			return ApiResult.error(paraTypeVO.getParaTypeName()+"下已存在该参数编码："+paraValue.getParaCode());
		}
		paraValueDao.save(paraValue);
		return ApiResult.ok();
	}

	@GetMapping("/{id}")
	@ApiOperation(value = "参数-根据id获取")
	
	public ApiResult<?> get(@PathVariable String id) {
		if(StringUtilsV2.isBlank(id)){
			return ApiResult.error("要查询的id不能为空");
		}
    	return ApiResult.data(paraValueDao.getById(id));
	}

	@LogAnnotation
	@PutMapping
	@ApiOperation(value = "参数-修改")
	//@PreAuthorize("hasAuthority('sys:paraValue:edit')")
	
	
	public ApiResult<?> update(@RequestBody ParaValue paraValue) {
		if (paraValue == null) {
			return ApiResult.error("修改数据不能为空");
		} 
		if (StringUtilsV2.isBlank(paraValue.getParaId())) {
			return ApiResult.error("要修改的数据ID不能为空");
		}
		if(StringUtilsV2.isBlank(paraValue.getParaCode())){
			return ApiResult.error("参数编码不能为空");
		}
		ParaValue local = paraValueDao.getById(paraValue.getParaId());
		if (IfStatusType.N.getCode().equals(local.getIsUpdate())) {
			return ApiResult.error("失败，该参数已被设置为不可修改");
		}
		ParaTypeVO paraTypeVO = paraTypeDao.getById(paraValue.getParaTypeId());
		if(paraTypeVO != null && paraTypeVO.getParaTypeName().contains("分辨率")){
			if(!paraValue.getParaName().contains("*") 
					|| paraValue.getParaName().indexOf("*") != paraValue.getParaName().lastIndexOf("*")
					|| paraValue.getParaName().indexOf("*") == 0
					|| paraValue.getParaName().indexOf("*") == paraValue.getParaName().length()-1){
				return ApiResult.error("分辨率格式必须是（数字*数字）");
			}else{
				String f = paraValue.getParaName().substring(0, paraValue.getParaName().indexOf("*"));
				if(!CommUtil.isNumeric(f)){
					return ApiResult.error("分辨率格式必须是（数字*数字）");
				}
				String l = paraValue.getParaName().substring(paraValue.getParaName().indexOf("*")+1);
				if(!CommUtil.isNumeric(l)){
					return ApiResult.error("分辨率格式必须是（数字*数字）");
				}
			}
		}
		String paraId = paraValueDao.getIdByCodeAnd(paraValue.getParaCode(),paraValue.getParaTypeId());
		if(StringUtilsV2.isNotBlank(paraId) && !paraId.equals(paraValue.getParaId())){
			return ApiResult.error(paraTypeVO.getParaTypeName()+"下已存在该参数编码："+paraValue.getParaCode());
		}
		LoginUser loginUser = UserUtil.getLoginUser();
		paraValue.setUpdateUserId(loginUser.getUserId());
		paraValueDao.update(paraValue);
		return ApiResult.ok();
	}

	@GetMapping("/listAll")
	@ApiOperation(value = "参数-参数列表")
	//@PreAuthorize("hasAuthority('sys:paraValue:query')")
	
	public List<ParaValue> ListAll() {
		return paraValueDao.findAll();
	}

	@PostMapping("/list")
	@ApiOperation(value = "列表（分页）")
	//@PreAuthorize("hasAuthority('sys:paraValue:query')")
	
	
	public PageInfo<ParaValueDetailVO> ListNew(@RequestBody PublicWhere strCon) {
		PageHelper.startPage(strCon.getOffset(), strCon.getLimit());
		//if (StringUtilsV2.isBlank(strCon.getSqlOrder())) {
			strCon.setSqlOrder("t.order_no ");
		//}
		PageHelper.orderBy(strCon.getSqlOrder());
		List<ParaValueDetailVO> list = paraValueDao.ParaValueList(strCon);
		PageInfo<ParaValueDetailVO> result = new PageInfo<ParaValueDetailVO>(list);
		return result;
	}

	@GetMapping
	@ApiOperation(value = "列表-分页-2.0")
	@Original
	public PageTableResponse ListNew2(PageTableRequest strCon) {
		PublicWhere where = new PublicWhere(strCon);
		PageHelper.startPage(where.getOffset(), where.getLimit());
		if (StringUtils.isBlank(where.getSqlOrder())) {
			where.setSqlOrder("t.create_time desc");
		}
		PageHelper.orderBy(where.getSqlOrder());
		List<ParaValueDetailVO> list = paraValueDao.ParaValueList(where);
		PageInfo<ParaValueDetailVO> result = new PageInfo<ParaValueDetailVO>(list);
		return new PageTableHandler(new PageTableHandler.CountHandler() {
			@Override
			public int count(PageTableRequest request) {
				return CommUtil.null2Int(result.getTotal());
			}
		}, new PageTableHandler.ListHandler() {
			@Override
			public List<ParaValueDetailVO> list(PageTableRequest request) {
				return result.getList();
			}
		}).handle(strCon);
	}
	
	@GetMapping("/listByParaTypeCode")
	@ApiOperation(value = "参数-参数列表")
	
	public ApiResult<?> List(String paraTypeCode) {
		if (StringUtilsV2.isNotBlank(paraTypeCode)) {
			return ApiResult.data(paraValueDao.findByParaTypeCode(paraTypeCode));
		} else {
			return ApiResult.error("参数类型编码不能为空");
		}
	}
	
	@GetMapping("/v2/listByParaTypeCode")
	@ApiOperation(value = "参数-参数列表")
	
	public ApiResult<?> List2(String paraTypeCode) {
		if (StringUtilsV2.isNotBlank(paraTypeCode)) {
			return ApiResult.data(paraValueDao.listSelectVOByParaTypeCode(paraTypeCode));
		} else {
			return ApiResult.error("参数类型编码不能为空");
		}
	}

	@DeleteMapping("/{id}")
	@ApiOperation(value = "参数-删除")
	//@PreAuthorize("hasAuthority('sys:paraValue:del')")
	
	public ApiResult<?> delete(@PathVariable String id) {
		if (StringUtilsV2.isBlank(id)) {
			return ApiResult.error("要删除的数据ID不能为空");
		}
		ParaValue local = paraValueDao.getById(id);
		if (IfStatusType.N.getCode().equals(local.getIsDel())) {
			return ApiResult.error("失败，该数据已被设置为不可删除");
		}
		paraValueDao.delete(id);
		return ApiResult.ok();
	}
	
	@SuppressWarnings("unchecked")
	@GetMapping("/getListVoParaValue")
	@ApiOperation(value = "参数-根据typeCode和Code获取VO")
	
	public ApiResult<?> getListVoParaValue(String paraTypeCode,String paraCode) {
		Gson gson = new Gson();
		List<SelectVO> sv;
		String pv = paraValueDao.getParaValueByTypeCodeAndCode(paraTypeCode,paraCode);
		if(StringUtilsV2.isNotBlank(pv)){
			sv = gson.fromJson(pv, ArrayList.class);
		}else{
			sv = new ArrayList<>();
		}
		return ApiResult.data(sv);
	}
	
	@GetMapping("/listSelect/{type}")
	@ApiOperation(value = "设备-有效搜索条件")
	
	public List<SelectVO> listValidSelect(@PathVariable String type) {
		switch (type) {
			case "DataStatusType":
				return DataStatusType.selectVOsNORMAL();
			default:
				return null;
		}
	}
}
